/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.ehcache.hibernate;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.xml.transform.stream.StreamResult;

import com.eelpo.common.xml.XMLMergeUtils;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.ConfigurationFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * <pre>
 * 
 * 多缓存配置管理类,处理缓存配置文件合并
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class MultiConfigAwareEhCacheRegionFactory extends AbstractMultiConfigAwareEhCacheRegionFactory {

	private static final Logger logger = LoggerFactory.getLogger(MultiConfigAwareEhCacheRegionFactory.class);

	public MultiConfigAwareEhCacheRegionFactory(Properties prop) {
		super(prop);
	}

	@Override
	protected Configuration parseConfiguration() {
		logger.debug("Configuring ehcache from classpath");
		return parseConfiguration(getMultiConfigFromClassPath());
	}

	@Override
	protected Configuration parseConfiguration(URL url) {
		logger.debug("Configuring ehcache from URL: {}", url);
		List<InputStream> inputStreams = getMultiConfigFromClassPath();
		return parseConfiguration(inputStreams);
	}

	/**
	 * <pre>
	 * 
	 * 获取classpath*:conf/ehcache*.xml匹配的所有Ehcache配置文件
	 * 
	 * <pre>
	 * @return 返回所有配置文件的输入流
	 */
	public List<InputStream> getMultiConfigFromClassPath() {
		try {
			List<InputStream> inputStreams = new LinkedList<InputStream>();
			Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:conf/ehcache*.xml");
			for (Resource resource : resources) {
				logger.info("Append ehcache config from [{}]", resource.getFilename());
				inputStreams.add(resource.getInputStream());
			}
			return inputStreams;
		} catch (IOException e) {
			logger.warn("No append ehcache config from classpath");
			return new LinkedList<InputStream>();
		}
	}

	private Configuration parseConfiguration(List<InputStream> inputStreams) {

		if (inputStreams.isEmpty()) {
			throw new IllegalArgumentException("No configuration found from classpath");
		}

		if (inputStreams.size() == 1) {
			return ConfigurationFactory.parseConfiguration(inputStreams.get(0));
		}

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		if (XMLMergeUtils.mergeFromInputStreams(inputStreams, new StreamResult(outputStream))) {
			ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return ConfigurationFactory.parseConfiguration(inputStream);
		}

		throw new IllegalStateException("Error configuring from config file");
	}
}
